<?php
/**
 * 图片管理控制器
 * 整个网站的所有图片均由此控制器进行管理
 * 其中包括图片列表、上传图片、创建图片文件夹、删除图片，搜索图片
 * 此图片管理移植于Opencart,但是图片处理是基于thinkphp自带的图片处理类
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
use Think\Controller;
use Common\Library\Page;
use Common\Library\Upload;
class ImageController extends CommonController{
	public function index(){
    	//筛选参数
        $filter_name=rtrim(str_replace(array('../', '..\\', '..', '*'), '',I('get.filter_name')),'/');
        //目录参数
        $directory=I('get.directory')?rtrim(C('IMAGE_DIR').str_replace(array('../', '..\\', '..'), '',str_replace(':','/',I('get.directory'))),'/'):rtrim(C('IMAGE_DIR'),'/');

        $images=array();
       
        // 获取目录列表
		$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
		if (!$directories) {
			$directories = array();
		}
		
		//获取文件列表
		$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);

		if (!$files) {
			$files = array();
		}
		//合并目录列表和文件列表
		$images = array_merge($directories, $files);
		
		$image_total=count($images);
		$Page=new Page($image_total,16);	
		$show=$Page->show();
		$images = array_splice($images, $Page->firstRow, $Page->listRows);		
		foreach ($images as $image) {
			$name=basename($image);
			if(is_dir($image)){
				$url = array(
					'directory'  => str_replace('/',':',substr($image, strlen(C('IMAGE_DIR'))))
				);
				if (I('get.target')) {
					$url['target'] =  I('get.target');
				}
				if (I('get.thumb')) {
					$url['thumb'] =  I('get.thumb');
				}
				$imgs[]=array(
					'image'		=>	$image,
					'thumb'		=>	'',
					'name'		=>	$name,
					'type'		=>	'directory',
					'path'  	=> 	rtrim(substr($image, strlen(C('IMAGE_DIR'))),'/'),
					'href'		=>	U('index',$url)
					);
			}elseif(is_file($image)){
				$imgs[]=array(
					'image'		=>	$image,
					'thumb'		=>	image_resize(substr($image, strlen(C('IMAGE_DIR'))),120,120),
					'name'		=>	$name,
					'type'		=>	'image',
					'path'  	=> 	substr($image, strlen(C('IMAGE_DIR'))),
					'href'		=>	C('HTTP_IMAGE') . '/images/' . substr($image, strlen(C('IMAGE_DIR')))
				);
			}
		}
		//上一级目录
		$url=array();
		if (I('get.directory')) {
			$pos = strrpos(I('get.directory'), ':');
			
			if ($pos) {
				$url['directory'] = substr(I('get.directory'), 0, $pos);
			}
		}
		if (I('get.target')) {
			$url['target'] = I('get.target');
		}
		if (I('get.thumb')) {
			$url['thumb']=I('get.thumb');
		}

		$directory=I('get.directory')?I('get.directory'):'';
		$this->assign('filter_name',$filter_name);
		$this->assign('target',I('get.target',''));
		$this->assign('thumb',I('get.thumb',''));
		$this->assign('upload',U('upload',array('directory'=>$directory)));
		$this->assign('folder',U('folder',array('directory'=>$directory)));
		$this->assign('parent',U('index',$url));
		$this->assign('images',$imgs);
		$this->assign('page',$show);
		$this->display();
	}

	public function upload() {
		$directory=I('get.directory')?I('get.directory'):'';
		$Upload = new Upload();
		// 设置附件上传大小
		$Upload->maxSize   =     3145728 ;
		$Upload->saveName  =	'';
		// 设置附件上传类型
    	$Upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
    	// 设置附件上传根目录
    	$Upload->rootPath  =     C('IMAGE_DIR'); 
    	$Upload->subName	=	'trim';
    	$Upload->savePath  = str_replace(':','/',$directory);
    	// 上传文件 
	    $info   =   $Upload->upload();
	    if(!$info) {// 上传错误提示错误信息
	        $json['error']=$Upload->getError();
	    }else{// 上传成功
	        $json['success']=L('success_upload_success');
	    }
	    $this->ajaxReturn($json,'JSON');
	}

	public function folder(){
		// Make sure we have the correct directory
		if (I('get.directory')) {
			$directory = rtrim(C('IMAGE_DIR') . str_replace(array('../', '..\\', '..'), '', str_replace(':','/',I('get.directory'))), '/');
		} else {
			$directory = C('IMAGE_DIR');
		}

		// Check its a directory
		if (!is_dir($directory)) {
			$json['error'] = L('error_parent_path');
		}

		if (!$json) {
			// Sanitize the folder name
			$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode(I('post.folder'), ENT_QUOTES, 'UTF-8')));

			// Validate the filename length
			if ((strlen($folder) < 3) || (strlen($folder) > 128)) {
				$json['error'] = L('error_file_name_format');
			}

			// Check if directory already exists or not
			if (is_dir($directory . '/' . $folder)) {
				$json['error'] = L('error_directory_exists');
			}
		}

		if (!$json) {
			mkdir($directory . '/' . $folder, 0777);
			chmod($directory . '/' . $folder, 0777);

			$json['success'] = L('success_create_directory');
		}
		$this->ajaxReturn($json,'JSON');
	}

	public function delete(){
		if (I('post.path')) {
			$paths = I('post.path');
		} else {
			$paths = array();
		}

		// Loop through each path to run validations
		foreach ($paths as $path) {
			$path = rtrim(C('IMAGE_DIR') . str_replace(array('../', '..\\', '..'), '', $path), '/');
			
			// Check path exsists
			if ($path == rtrim(C('IMAGE_DIR'),'/')) {
				$json['error'] = L('error_directory_delete_failed');

				break;
			}
		}

		if (!$json) {
			// Loop through each path
			foreach ($paths as $path) {
				$path = rtrim(C('IMAGE_DIR') . str_replace(array('../', '..\\', '..'), '', $path), '/');
				
				// If path is just a file delete it
				if (is_file($path)) {
					unlink($path);

				// If path is a directory beging deleting each file and sub folder
				} elseif (is_dir($path)) {
					$files = array();

					// Make path into an array
					$self=$path;
					$path = array($path . '/*');
					$path[]=$self;
					// While the path array is still populated keep looping through
					while (count($path) != 0) {
						$next = array_shift($path);

						foreach (glob($next) as $file) {
							// If directory add to path array
							if (is_dir($file)) {
								$path[] = $file . '/*';
							}

							// Add the file to the files to be deleted array
							$files[] = $file;
						}
					}
					
					// Reverse sort the file array
					rsort($files);

					foreach ($files as $file) {
						// If file just delete
						if (is_file($file)) {
							unlink($file);

						// If directory use the remove directory function
						} elseif (is_dir($file)) {
							rmdir($file);
						}
					}
				}
			}

			$json['success'] = L('success_delete');
		}
		$this->ajaxReturn($json,'json');
	}
}